﻿using System;
using System.Windows.Forms;

namespace Nextensions.GUI.Extensions
{
    public static class FormExtension
    {
        private static object _lock = new object();
        private static int? _minTabIndex;
        private static Control _target = null;

        public static void AutoSelectInputField(this Form Form)
        {
            lock (_lock)
            {
                _minTabIndex = null;
                IterateInputFields(Form);
                if (_target == null)
                    return;

                _target.Focus();
            }
        }

        private static void IterateInputFields(Control Control)
        {
            foreach (Control child in Control.Controls)
            {
                // Search for the first empty field so we can select it for the user
                if (String.IsNullOrEmpty(child.Text) && (!_minTabIndex.HasValue || child.TabIndex < _minTabIndex))
                {
                    _minTabIndex = child.TabIndex;
                    _target = child;
                }

                IterateInputFields(child);
            }
        }
    }
}
